/**
 * UI thread of MapActivity. 
 * Sub-activity of ShuttleMainActivity.
 * 
 * @author Alican Ozgoren
 * @version 12/14/2012
 */

package edu.brockport.shuttleapp;

import java.util.List;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

import edu.brockport.shuttleapp.database.DatabaseInquirer;


public class ShuttleMapActivity extends MapActivity 
{	
	private MapView mapView;
	private MapController controller;
	private ZoomControls zoomControls;
	private Button showRouteButton;
	private Bundle myBundle;
	private ScrollView routeDisplayLayout;
	private boolean isRouteDialogDisplayed = false;
	private boolean reverseStatus; 
	private Thread toastWaiter = new Thread()
	{
        @Override
        public void run() 
        {
        	try 
        	{
                Thread.sleep(2000); // As I am using LENGTH_SHORT in Toast
                ShuttleMapActivity.this.finish();
            } 
        	catch (Exception e) {
                e.printStackTrace();
            }
         }  
	};
	
	private double x;
	private double y;
	private String name;

	   //----------------------------------------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shuttle_map);
        initUI();
        doYourJob();
        checkSavedState(savedInstanceState);
    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        getMenuInflater().inflate(R.menu.activity_shuttle_map, menu);
        return true;
    }*/

    //----------------------------------------------------------
	@Override
	protected boolean isRouteDisplayed() 
	{
		return false;
	}
	
	//----------------------------------------------------------
	private void checkSavedState(Bundle savedInstanceState)
	{
		if (savedInstanceState != null) 
		{
			String title = savedInstanceState.getString("title");
			TextView pinInfoView = (TextView) findViewById(R.id.showPinInfo);
			pinInfoView.setText(title);
		}
	}
	
	//----------------------------------------------------------
	private void initUI()
	{
		mapView = (MapView) findViewById(R.id.mapView);
		controller = mapView.getController();
		showRouteButton = (Button) findViewById(R.id.showRouteButton);
		routeDisplayLayout = (ScrollView) findViewById(R.id.showRouteLayoutParent);
		zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
		zoomControls.setOnZoomInClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				controller.zoomIn();
			}
		});
		zoomControls.setOnZoomOutClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				controller.zoomOut();
			}
		});
		showRouteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View arg0) 
			{
				if(isRouteDialogDisplayed)	
				{
					routeDisplayLayout.setVisibility(View.GONE);
					isRouteDialogDisplayed = false;
				}
				else
				{
					routeDisplayLayout.setVisibility(View.VISIBLE);
					isRouteDialogDisplayed = true;
				}
			}
		});
		
	}
	
	//----------------------------------------------------------
	private void getLocationDataFromMainActivity()
	{
		String locX = myBundle.getString("X"); 
	    String locY = myBundle.getString("Y"); 
	    name = myBundle.getString("name");
	    
	    if(locX == null || locY == null)
	    {
	    	Utilities.toaster(this, "Unexpected problem!");
	    	toastWaiter.start();
	    }
		
		// If the activity is still running, convert locX and locY
		x = Double.valueOf(locX);
		y = Double.valueOf(locY);
	}
	
	//----------------------------------------------------------
	private void getPathDataFromMainActivity()
	{
		List mapOverlays = mapView.getOverlays();
		GeoPoint firstPoint = null;
		
		int seq_counter = myBundle.size() - 1;
		for(int cnt = 0; cnt < myBundle.size() - 1; cnt++)
		{
			String[] routeInfo = null;
			if(!reverseStatus)
			{
				routeInfo = myBundle.getString(Integer.toString(cnt + 1)).split(";");
			}
			else
			{
				routeInfo = myBundle.getString(Integer.toString(seq_counter--)).split(";");
			}
			String name = routeInfo[0];
			double lat = Double.valueOf(routeInfo[2]);
			double lon = Double.valueOf(routeInfo[1]);
			boolean selected = Boolean.valueOf(routeInfo[3]);
			boolean departure = Boolean.valueOf(routeInfo[4]);
			Drawable drawable = getDrawable(cnt + 1, selected);
			CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(drawable, this);
			GeoPoint stopLoc = new GeoPoint((int) (lon * 1E6), (int) (lat * 1E6));
			OverlayItem overlayItem = new OverlayItem(stopLoc, name, "");
			itemizedOverlay.addOverlay(overlayItem);
			mapOverlays.add(itemizedOverlay);
			
			if(departure)
				firstPoint = stopLoc;
		}
	
		mapView.setSatellite(false);
		mapView.invalidate();
		controller.animateTo(firstPoint);
		controller.setZoom(16);
	}
	
	//----------------------------------------------------------
	private void createRouteDisplayLayout()
	{
		// Get reverse status
		reverseStatus = DatabaseInquirer.getReverseStatus();
		LinearLayout parent = (LinearLayout) findViewById(R.id.showRouteLayoutChild);
		parent.setOrientation(LinearLayout.VERTICAL);
		RelativeLayout.LayoutParams params;
		
		int seq_counter = myBundle.size() - 1;
		for(int cnt = 0; cnt < myBundle.size() - 1; cnt++)
		{
			// Get the required info from bundle 
			String[] routeInfo = null;
			if(!reverseStatus)
			{
				routeInfo = myBundle.getString(Integer.toString(cnt + 1)).split(";");
			}
			else
			{
				routeInfo = myBundle.getString(Integer.toString(seq_counter--)).split(";");
			}
			
			String name = routeInfo[0];
			boolean selected = Boolean.valueOf(routeInfo[3]);
			
			// Start building the layout step by step 
			// Step-0: Create a row
			RelativeLayout row = new RelativeLayout(this);
			
			// Step-1: Sequence
			TextView sequenceView = (TextView) getLayoutInflater().inflate(R.layout.route_count, null);
			sequenceView.setId(1);
			String sequence = Integer.toString(cnt + 1) + ".";
			sequenceView.setText(sequence);
			params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			row.addView(sequenceView, params);
			
			// Step-2: Stop name
			TextView nameView;
			if(selected)
				nameView = (TextView) getLayoutInflater().inflate(R.layout.route_textview_selected, null);
			else
				nameView = (TextView) getLayoutInflater().inflate(R.layout.route_textview, null);
			//nameView.setOnFocusChangeListener(getOnFocusChangeListener());
			nameView.setId(2);
			nameView.setText(name);
			params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.RIGHT_OF, sequenceView.getId());
			row.addView(nameView, params);
			
			// Step-3: Add row to parent
			parent.addView(row);
		}
	}
	
	//----------------------------------------------------------
	private void doYourJob()
	{
		// Get the purpose
        myBundle = getIntent().getExtras();
        String purpose = "";
        if(myBundle != null)
        {
        	purpose = myBundle.getString("purpose");
        }
        else
        {
        	Utilities.toaster(this, "Unexpected problem!");
	    	toastWaiter.start();
        }
        
        // Do your job according to purpose
        if(purpose.equals("map"))
        {
        	showRouteButton.setVisibility(View.GONE);
        	getLocationDataFromMainActivity();
        	GeoPoint stopLoc = new GeoPoint((int) (x * 1E6), (int) (y * 1E6));
    		createLocationPin(stopLoc);
    		mapView.setSatellite(true);
    		mapView.invalidate();
    		controller.animateTo(stopLoc);
    		controller.setZoom(18);
        }
        else
        if(purpose.equals("path"))
        {
        	showRouteButton.setVisibility(View.VISIBLE);
        	createRouteDisplayLayout();
        	getPathDataFromMainActivity();
        }
	}	
	
	//----------------------------------------------------------
	private void createLocationPin(GeoPoint loc) 
	{
		List mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(R.drawable.location);
		CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(drawable, this);
		OverlayItem overlayItem = new OverlayItem(loc, name, "");
		itemizedOverlay.addOverlay(overlayItem);
		mapOverlays.add(itemizedOverlay);
		mapView.invalidate();
	}
	
	//----------------------------------------------------------
	private Drawable getDrawable(int sequence, boolean selected)
	{
		Drawable pin = null;
		if(!selected)
		{
			switch(sequence)
			{
				case 1: pin = this.getResources().getDrawable(R.drawable.pin_1); break;
				case 2: pin = this.getResources().getDrawable(R.drawable.pin_2); break; 
				case 3: pin = this.getResources().getDrawable(R.drawable.pin_3); break;
				case 4: pin = this.getResources().getDrawable(R.drawable.pin_4); break;
				case 5: pin = this.getResources().getDrawable(R.drawable.pin_5); break;
				case 6: pin = this.getResources().getDrawable(R.drawable.pin_6); break;
				case 7: pin = this.getResources().getDrawable(R.drawable.pin_7); break;
				case 8: pin = this.getResources().getDrawable(R.drawable.pin_8); break;
				case 9: pin = this.getResources().getDrawable(R.drawable.pin_9); break;
				case 10: pin = this.getResources().getDrawable(R.drawable.pin_10); break;
				case 11: pin = this.getResources().getDrawable(R.drawable.pin_11); break;
				case 12: pin = this.getResources().getDrawable(R.drawable.pin_12); break;
				case 13: pin = this.getResources().getDrawable(R.drawable.pin_13); break;
				case 14: pin = this.getResources().getDrawable(R.drawable.pin_14); break;
				case 15: pin = this.getResources().getDrawable(R.drawable.pin_15); break;
				case 16: pin = this.getResources().getDrawable(R.drawable.pin_16); break;
			}
		}
		else
		{
			switch(sequence)
			{
				case 1: pin = this.getResources().getDrawable(R.drawable.pin_1_selected); break;
				case 2: pin = this.getResources().getDrawable(R.drawable.pin_2_selected); break; 
				case 3: pin = this.getResources().getDrawable(R.drawable.pin_3_selected); break;
				case 4: pin = this.getResources().getDrawable(R.drawable.pin_4_selected); break;
				case 5: pin = this.getResources().getDrawable(R.drawable.pin_5_selected); break;
				case 6: pin = this.getResources().getDrawable(R.drawable.pin_6_selected); break;
				case 7: pin = this.getResources().getDrawable(R.drawable.pin_7_selected); break;
				case 8: pin = this.getResources().getDrawable(R.drawable.pin_8_selected); break;
				case 9: pin = this.getResources().getDrawable(R.drawable.pin_9_selected); break;
				case 10: pin = this.getResources().getDrawable(R.drawable.pin_10_selected); break;
				case 11: pin = this.getResources().getDrawable(R.drawable.pin_11_selected); break;
				case 12: pin = this.getResources().getDrawable(R.drawable.pin_12_selected); break;
				case 13: pin = this.getResources().getDrawable(R.drawable.pin_13_selected); break;
				case 14: pin = this.getResources().getDrawable(R.drawable.pin_14_selected); break;
				case 15: pin = this.getResources().getDrawable(R.drawable.pin_15_selected); break;
				case 16: pin = this.getResources().getDrawable(R.drawable.pin_16_selected); break;
			}
		}
		
		return pin;
	}
	
	//----------------------------------------------------------
	@Override
	protected void onSaveInstanceState(Bundle outState) 
	{
		TextView pinInfoView = (TextView) findViewById(R.id.showPinInfo);
		outState.putString("title", (String) pinInfoView.getText());
		
		super.onSaveInstanceState(outState);
	}
	
	//----------------------------------------------------------
	public void onClick(View v) 
	{
        v.setSelected(true);
    } 
	
}
